package com.zkingsoft.actions.admin;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.alipay.sign.MD5;
import com.zkingsoft.model.ExtensionDetail;
import com.zkingsoft.model.Userdata;
import com.zkingsoft.model.Users;
import com.zkingsoft.model.WeixinUserInfo;
import com.zkingsoft.plugin.aes.AesException;
import com.zkingsoft.plugin.aes.WXBizMsgCrypt;
import com.zkingsoft.plugin.message.sendsms;
import com.zkingsoft.pojo.Result;
import com.zkingsoft.services.ExtensionDetailService;
import com.zkingsoft.services.UserdataService;
import com.zkingsoft.services.UsersService;

/**
 * @description 登录用户信息action
 * @author xieguangya
 * @email 935090232@qq.com
 * @date 2016-07-18
 */
@Controller
@RequestMapping(value = "/admin/login")
public class UserController extends BaseController {

	@Resource
	private UsersService userService;
	@Resource
	private ExtensionDetailService extensionService;
	@Resource
	private UserdataService userDataService;


	/**
	 *微信 用户登录绑定推广人
	 */
	@RequestMapping(value = "/getUserInfo")
	public @ResponseBody Result createUserInfo(String weixinId){
		System.out.println("绑定推广人START......");
		
		Result result = new Result();
		ExtensionDetail extensionDetail = extensionService.findByWeiXinId(weixinId);
		if(extensionDetail!=null){//绑定了推广人
			System.out.println(">>>>>已经绑定推广人<<<<<");
			Userdata userData = userDataService.findByWeixinId(weixinId);
			
			//mlg增加，判断用户是否已登录
			if(userData == null) {
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("用户未注册");
				return result;
			}
			/*//mlg修改
			extensionDetail.setUserId(userData.getUserid());
			extensionDetail.setStatus(2);//已登录
			int num = extensionService.modify(extensionDetail);*/
			if(extensionDetail.getUserId()==null){
				//mlg修改
				System.out.println(">>>>>进入返钱<<<<<");
				extensionDetail.setUserId(userData.getUserid());
				extensionDetail.setStatus(2);//已登录
				int num = extensionService.modify(extensionDetail);
				
				if(num>0){
					//返利给推广人
					Users user = userService.findById(extensionDetail.getUserParentId());
					/*mlg,返利改为100钻*/
					Userdata pUserData = userDataService.findByWeixinId(user.getWeixinId());
					if(pUserData == null) {
						result.setCode(Result.STATUS_FALSE);
						result.setMsg("未绑定推广人");
						return result;
					}
					int diamondnum = pUserData.getDiamondnum() 
							+ (extensionDetail.getMoney()==null ? 0 : extensionDetail.getMoney().intValue());
					pUserData.setDiamondnum(diamondnum);
					int res = userDataService.modify(pUserData);
//					Double money = extensionDetail.getMoney()+(user.getExtensionMoney()==null?0:user.getExtensionMoney());
//					user.setExtensionMoney(money);
//					int res = userService.modify(user);
					if(res>0){
						result.setCode(Result.STATUS_TRUE);
						result.setMsg("返利成功");
					}
				}
			}else{
				result.setCode(Result.STATUS_OLD);
				result.setMsg("老用户");
			}
			
		}else{//未绑定推广人
			result.setCode(Result.STATUS_FALSE);
			result.setMsg("未绑定推广人");
		}
		return result;
	}
	
	
	/**
	 *微信公众号测试接口
	 * @throws AesException 
	 */
	@RequestMapping(value = "/test")
	public @ResponseBody String weixinTest(String signature,String timestamp,String nonce,String echostr) throws AesException{
		String sToken = "qetuo2468";
		String sCorpID = "wx5f684362422f302e";
		String sEncodingAESKey = "hTCBHidy8qmJXAPVWIATsZNGoIlML56UW49tPXoMK5d";
		
		WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
				String sVerifyMsgSig = signature;
				String sVerifyTimeStamp = timestamp;
				String sVerifyNonce = nonce;
				String sVerifyEchoStr = echostr;
				String sEchoStr = ""; //需要返回的明文
				try {
					sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,sVerifyNonce, sVerifyEchoStr);
					// 验证URL成功，将sEchoStr返回
					// HttpUtils.SetResponse(sEchoStr);
				} catch (Exception e) {
					//验证URL失败，错误原因请查看异常
					e.printStackTrace();
				}
				return sEchoStr;
	}
	
	@RequestMapping(value = "/test1")
	public @ResponseBody String weixinTest1(WeixinUserInfo info){
		return "openId==>"+info.getOpenid();
	}
	/**
	 * 登录时生成token
	* @Title: token 
	* @Description: TODO 
	* @param @param weixinId
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	@RequestMapping(value = "/token")
	public @ResponseBody Result token(int gameId){
		Result result = new Result();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String random = RandomStringUtils.random(20,"1234567890qwertyuioplkjhgfdsazxcvbnm_#$%&()QWERTYUIOPLKJHGFDSAZXCVBNM");
			String token = MD5.sign(random, gameId+"", "utf-8");
			System.out.println("token = "+token);
			userDataService.updateToken(token,gameId);
			result.setCode(Result.STATUS_TRUE);
			map.put("token", token);
			result.setResult(map);
			result.setMsg("token获取成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(Result.STATUS_FALSE);
			result.setMsg("token获取失败");
		}
		return result;
	}
	
	@RequestMapping(value = "/msgcode")
	public @ResponseBody Result msgcode(String tel){
		Result result = new Result();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			result.setCode(Result.STATUS_TRUE);
			map.put("code", sendsms.sendSms(tel));
			result.setResult(map);
			result.setMsg("短信验证码发送成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(Result.STATUS_FALSE);
			result.setMsg("短信验证码发送失败！");
		}
		return result;
	}
}